package com.pandora.credit.service.impl;

import com.pandora.common.util.*;
import com.pandora.credit.entity.Credit;
import com.pandora.credit.entity.Customer;
import com.pandora.credit.entity.History;
import com.pandora.credit.mongo.entity.MongoPandoraCredit;
import com.pandora.credit.mongo.service.MongoPandoraCreditService;
import com.pandora.credit.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * @author developer
 */
@Service
public class CommonServiceImpl implements CommonService {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private CreditService creditService;
    @Autowired
    private MongoPandoraCreditService mongoPandoraCreditService;
    @Autowired
    private CustomerService customerService;
    @Autowired
    private HistoryService historyService;
    @Autowired
    private VersionService versionService;

    @Override
    public Map<String, Object> getCreditFromMongoDb(int type, int length, int nextIdP, int hot, long bank,
                                                    int recommend, String version, String platform, long loanType,
                                                    int frontNumber) {
        Credit find = new Credit();
        if(nextIdP <= 0){
            nextIdP = 1;
        }
        if(length <= 0){
            if(frontNumber <= 0){
                length = Constants.DEFAULT_PAGE_LENGTH;
            }else {
                length = frontNumber;
            }
        }
        int offset = length * (nextIdP - 1);

        find.setIsValid(Constants.CREDIT_STATUS_VALID);
        find.setType(type);
        find.setOffset(offset);
        if(recommend > 0){
            find.setRecommend(recommend);
        }
        if(hot >= 0){
            find.setIsHot(hot);
        }
        if(bank >= 0){
            find.setBankId(bank);
        }
        if(loanType >= 0){
            find.setBankId(loanType);
        }
        find.setLimit(length);

        List<Credit> items = creditService.getByCondition(find);
        int totalItems = items.size();
        Integer nextId = null;
        if(totalItems/length >= nextIdP){
            nextId = nextIdP + 1;
        }
        List<Long> itemIds = new LinkedList<Long>();
        for(Credit credit : items){
            itemIds.add(credit.getId());
        }
        Map<Long, MongoPandoraCredit> itemDict = new LinkedHashMap<Long, MongoPandoraCredit>();
        List<MongoPandoraCredit> itemsObj = mongoPandoraCreditService.queryByIds(itemIds);
        for(MongoPandoraCredit mongoItem : itemsObj){
            itemDict.put(mongoItem.getId(), mongoItem);
        }
        Map<String, Object> reMap = new LinkedHashMap<String, Object>();
        List<MongoPandoraCredit.MongoPandoraCreditItem> reLi = new LinkedList<MongoPandoraCredit.MongoPandoraCreditItem>();
        for(Credit c : items){
            MongoPandoraCredit mongoItem = itemDict.get(c.getId());
            if(mongoItem != null){
                long id = mongoItem.getId();
                MongoPandoraCredit.MongoPandoraCreditItem item = mongoItem.getItem();
                item.setId(id);
                item.setCount(c.getAppCount()>0?c.getAppCount():0);
                if(item.verifySize() <= 5){
                    item.setRecommend(c.getRecommend());
                }
                else {
                    item.setRecommend(c.getRecommend()%1000+100000);
                    item.setTypeId(item.getAssortId());
                }
                reLi.add(item);
            }
        }

        reMap.put("next_id", nextId);
        reMap.put("resp_items", reLi);
        return reMap;
    }

    @Override
    public long getCustomerIdByMobile(String mobile) {
        String cusIdStr = JedisUtil.get(Constants.BUSINESS_REDIS_URL,
                StringUtils.getStrParam(Constants.MOBILE_CUS_ID_KEY, mobile));
        if(VerifyUtil.isEmpty(cusIdStr)){
            Customer cus = customerService.getByMobile(mobile);
            if(cus != null){
                cusIdStr = String.valueOf(cus.getId());
                JedisUtil.set(Constants.BUSINESS_REDIS_URL,
                        StringUtils.getStrParam(Constants.MOBILE_CUS_ID_KEY, mobile),
                        cusIdStr,
                        Constants.MOBILE_CUSTOMER_ID_TIME_OUT);
            }
        }
        if (VerifyUtil.isEmpty(cusIdStr)) {
            return -1;
        }
        return Long.parseLong(cusIdStr);
    }

    @Override
    public Map<String, Object> getHistories(int dbType, long customerId, int pageLength, String updateTime) {
        if(pageLength == 0){
            pageLength = Constants.PAGE_LENGTH_DEFAULT;
        }
        List<Long> docIds = new LinkedList<Long>();
        List<History> historyList = historyService.selectByUpdateTime(customerId, dbType, updateTime, pageLength);
        for(History h : historyList){
            docIds.add(h.getDocId());
        }
        String nextId = null;
        if(historyList != null && historyList.size() > pageLength){
            nextId = DateUtil.getDateStr(historyList.get(pageLength).getUpdateTime());
            docIds = new LinkedList<Long>();
            for(int i = 0; i <= pageLength; i++){
                docIds.add(historyList.get(i).getDocId());
            }
        }
        Map<Long, Object> resItemMap = new LinkedHashMap<Long, Object>();
        List<MongoPandoraCredit> resObj = mongoPandoraCreditService.queryByTypeIds(dbType, docIds);
        for(MongoPandoraCredit m : resObj){
            resItemMap.put(m.getId(), m.getItem());
        }
        List<Object> resList = new LinkedList<Object>();
        for(Long id : docIds){
            if(resItemMap.containsKey(id)){
                resList.add(resItemMap.get(id));
            }
        }
        Map<String, Object> re = new LinkedHashMap<String, Object>();
        re.put("res_list", resList);
        re.put("next_id", nextId);
        return re;
    }

    @Override
    public int getAppStatusLimit(String ua) {
        int value = Constants.VERSION_STATUS_ONLINE;
        if(!VerifyUtil.isEmpty(ua)){
            Map<String, String> pvMap = UserAgentUtil.getVersionByUserAgent(ua);
            if(!VerifyUtil.isEmpty(pvMap.get(MagicConst.APP_STATUS_KEY_P))
                    && !VerifyUtil.isEmpty(pvMap.get(MagicConst.APP_STATUS_KEY_V))){
                value = versionService.getStatusByType(
                        pvMap.get(MagicConst.APP_STATUS_KEY_P),
                        pvMap.get(MagicConst.APP_STATUS_KEY_V),
                        Constants.ITEM_STATUS_VALID);
                if(value == -1){
                    value = Constants.VERSION_STATUS_ONLINE;
                }
            }
        }
        return value;
    }

}
